//
//  NYOPMovieDetailViewController.m
//  Kokozu
//
//  Created by Bismarrck on 11-7-12.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "NYOPMovieDetailViewController.h"
#import "BidResultViewController.h"

@implementation NYOPMovieDetailViewController

@synthesize movieNameLabel;
@synthesize movieIntroLabel;
@synthesize movieAvgPriceLabel;
@synthesize timeButton;
@synthesize ticketNumButton;
@synthesize monthButton;
@synthesize dayButton;
@synthesize commCircleButton;
@synthesize myPriceField;
@synthesize NYOPRecord;
@synthesize book_time;
@synthesize priceSlider;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [movieNameLabel release];
    [movieIntroLabel release];
    [movieAvgPriceLabel release];
    [monthButton release];
    [dayButton release];
    [timeButton release];
    [ticketNumButton release];
    [myPriceField release];
    [NYOPRecord release];
    [book_time release];
    
    [super dealloc];
}

- (id)initWithMovieRecord:(MovieRecord *)aRecord
{
    self = [super init];
    if (self) {
        self.NYOPRecord = (NYOPMovieRecord *)aRecord;
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
    }
    
    return self;
}

#pragma mark - View lifecycle

- (void)configureButtonTitle
{
    [self.ticketNumButton setTitle:ticket_num_ forState:UIControlStateNormal];
    [self.commCircleButton setTitle:commArea_ forState:UIControlStateNormal];
    [self.timeButton setTitle:self.book_time forState:UIControlStateNormal];
}

- (void)configure
{
    // Configure the main scroll view
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    // Set the movie name
    self.movieNameLabel.text = [self.NYOPRecord movieName];
    
    // Set the movie intro info
    self.movieIntroLabel.text = [self.NYOPRecord movieIntro];
    
    // Set the movie price info
    self.movieAvgPriceLabel.text = [self priceLabelwithPrice:55];
    self.myPriceField.text = @"10元";
    
    // Set the default value
    ticket_num_ = @"1张";
    self.book_time = @"";
    
    // Set the user area
    if (USER_DEFAULT_COMM_AREA) {
        commArea_ = USER_DEFAULT_COMM_AREA;
    }
    else {
        commArea_ = @"";
    }
    
    [self configureButtonTitle];
}

- (void)viewDidLoad
{
    self.myPriceField.keyboardType = UIKeyboardTypeNumberPad;
    self.myPriceField.textAlignment = UITextAlignmentCenter;
    self.myPriceField.delegate = self;
    
    self.priceSlider.continuous = YES;
    self.priceSlider.maximumValue = 99;
    self.priceSlider.minimumValue = 10;
    [self.priceSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [super viewDidLoad];
    
    // Load the cell nib
    self.cellNib = [UINib nibWithNibName:@"DetailTableViewCell" bundle:nil];
    
    // Configure the view
    [self configure];
    
    // Set the nav bar left item, pop back item
    [self createBarItemOn:kNavBarItemSideLeft frame:kNavBarLeftItemFrame title:@"返回" target:self action:@selector(popBackToLastViewController)];
    
    // Set the nav bar title
    [self addTitleToNavigationBar:@"影片详情"];
}


- (void)keyboardWillShow:(NSNotification *)note {  
    // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(doneButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        //if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)// OS 3.0
		if(([[keyboard description] hasPrefix:@"<UIPeripheralHostView"] == YES) ||(([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)))
            [keyboard addSubview:doneButton];
    }
}

- (void)doneButtonPressed {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [myPriceField resignFirstResponder];
}

#pragma mark -
#pragma mark UITextField Delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView beginAnimations:@"showKeyboardAnimation" context:nil];
    [UIView setAnimationDuration:0.30];
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y- 100, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.30];
    CGRect rect = self.view.frame;
    rect.origin.y += 100;
    self.view.frame = rect;
    [UIView commitAnimations];
  
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    self.movieNameLabel = nil;
    self.monthButton= nil;
    self.dayButton = nil;
    self.movieIntroLabel = nil;
    self.goButton = nil;
    self.movieAvgPriceLabel = nil;
    self.myPriceField = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (IBAction)goButtonPressed
{
    BidResultViewController *viewController = [[BidResultViewController alloc] initWithTitle:[self.NYOPRecord movieName]];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

- (IBAction)buttonPressed:(UIButton *)button
{
    NSInteger tag = [button tag];
    
    if (tag == kTicketNumButtonTag) {
        actionSheet_ = [self actionSheetWithType:PICKER_NUM];
    }
    else if (tag == kCommCircleButtonTag) {
        NSMutableArray *circle_array = [[NSMutableArray alloc] init];
        for (int i = 0; i < 4; i++) {
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int j = 0; j < 5; j++) {
                CommArea *area = [[CommArea alloc] init];
                area.areaName = [NSString stringWithFormat:@"子商圈%d%d",i,j];
                [array addObject:area];
                [area release];
            }
            CommCircle *aCircle = [[CommCircle alloc] init];
            aCircle.commAreas = array;
            aCircle.circleName = [NSString stringWithFormat:@"商圈%d", i];
            [circle_array addObject:aCircle];
            [aCircle release];
        }
        
        CustomTabBarViewController *sharedController = [CustomTabBarViewController sharedTabBarController];
        [sharedController.tabBar setHidden:YES];
        LocationViewController *locationViewController = [[LocationViewController alloc] initWithStyle:UITableViewStylePlain delegate:self commCirles:circle_array];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:locationViewController];
        locationViewController.view.frame = CGRectMake(0, 0, 320, 480);
        [sharedController.view bringSubviewToFront:navigationController.view];
        [self presentModalViewController:navigationController animated:YES];
        [locationViewController release];
    }
    else {
        CustomTabBarViewController *sharedController = [CustomTabBarViewController sharedTabBarController];
        [sharedController.tabBar setHidden:YES];
        DateWheelViewController *viewController = [[DateWheelViewController alloc] initWithDelegate:self];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
        viewController.view.frame = CGRectMake(0, 0, 320, 480);
        [sharedController.view bringSubviewToFront:navigationController.view];
        [self presentModalViewController:navigationController animated:YES];
        [viewController release];
    }
}

- (void)selectionDone
{
    NSString *changeContent = [self pickerView:self.dataPicker titleForRow:self.wantTicketsNum forComponent:0];
    
    NSLog(@"%@",changeContent);
    
    ticket_num_ = changeContent;
    [actionSheet_ dismissWithClickedButtonIndex:0 animated:YES];
    [self configureButtonTitle];
}

#pragma mark - location delegate

- (void)commAreaDidChanged
{
    commArea_ = USER_DEFAULT_COMM_AREA;
    
    NSLog(@"%@", commArea_);
    
    [self configureButtonTitle];
}

#pragma mark -

- (void)dateDidFinishChoose
{
    self.book_time = [[NSUserDefaults standardUserDefaults] valueForKey:@"my_date_time"];
    
    [self configureButtonTitle];
}

- (void)valueChanged:(id)sender
{
    UISlider *slider = (UISlider *)sender;
    
    myPriceField.text = [NSString stringWithFormat:@"%.0f元", slider.value];
}


@end
